package com.timguan.render.dataprocessor.processor;

import com.timguan.render.dataapi.api.ICmsDataManager;
import com.timguan.render.dataapi.domain.CmsDataDO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * 查询cms_data表获取对应的数据
 * Created by guankaiqiang on 2015/3/21.
 */
public class PaginationDataListProcessor extends DataProcessor {
    public static final int PAGE_SIZE = 20;
    @Autowired
    private ICmsDataManager cmsDataManagerImpl;

    protected List<Object> execute(CommonParametersWrapper wrapper, Map<String, String> params) {
        if (params != null && params.get(PROCESSOR_PARAM_DATALISTID) != null) {
            final int listId = Integer.valueOf(params.get(PROCESSOR_PARAM_DATALISTID));
            //获取模块的页码
            int pageNumber = StringUtils.isBlank(params.get(PAGE_NUMBER_PARAM)) ?
                    1 : Integer.valueOf(params.get(PAGE_NUMBER_PARAM));
            List<CmsDataDO> cmsDataDOs = cmsDataManagerImpl.selectByListId(listId);
            int totalNumber = cmsDataDOs.size();
            if (pageNumber > 0 && totalNumber > (pageNumber - 1) * PAGE_SIZE) {
                int start = (pageNumber - 1) * PAGE_SIZE;
                int end = totalNumber > pageNumber * PAGE_SIZE ?
                        (pageNumber == 1 ? PAGE_SIZE : pageNumber * PAGE_SIZE + 1): totalNumber;
                cmsDataDOs = cmsDataDOs.subList(start, end);
                return appendSpm(wrapper, cmsDataDOs, start);
            }
        }
        return null;
    }



    @Override
    public void afterPropertiesSet() throws Exception {
        needCreateDatalistWhenUsed = true;
        description = "分页(APP仅页面最末使用有效)";
    }
}
